package cn.daniellee.plugin.rs.menu;

import cn.daniellee.plugin.rs.RestrictedShop;
import cn.daniellee.plugin.rs.core.ShopCore;
import cn.daniellee.plugin.rs.model.PlayerData;
import cn.daniellee.plugin.rs.model.Shop;
import cn.daniellee.plugin.rs.model.ShopItem;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ShopMenu {

	public static Inventory generate(Shop shop, PlayerData playerData) {
		Inventory menu = Bukkit.createInventory(new ShopMenuHolder(), 54, (shop.getTitle() + " " + RestrictedShop.getInstance().getConfig().getString("menu.refresh-at", "&aDeadline: [{refreshAt}]").replace("{refreshAt}", new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date(playerData.getGenerateAt() + shop.getRefreshInterval())))).replace("&", "§"));

		// 填充角
		int[] cornerPosition = new int[]{ 0, 4, 8, 45, 49, 53 };
		for (int i : cornerPosition) menu.setItem(i, Common.getCorner());
		// 填充边
		int[] borderPosition = new int[]{ 1, 3, 5, 7, 9, 17, 36, 44, 46, 48, 50, 52 };
		for (int i : borderPosition) menu.setItem(i, Common.getBorder());

		// 计算第一个商品显示的位置
		int origin = playerData.getIndexList().length > 14 ? 13 : 22;

		for (int i = 0; i < playerData.getIndexList().length; i++) {
			ShopItem shopItem = shop.getPurchaseItems().get(playerData.getIndexList()[i]);
			int sellableNumber = playerData.getPurchaseNumbers()[i] * (100 + playerData.getPercentage()) / 100 - playerData.getSoldNumbers()[i];
			menu.setItem(i % 2 == 0 ? (origin + i / 7 * 9) + i / 2 : (origin + i / 7 * 9) - (i + 1) / 2, ShopCore.generateShopItem(shopItem, sellableNumber, playerData.getSoldNumbers()[i], playerData.getPercentage()));
		}

		return menu;
	}


	public static class ShopMenuHolder implements InventoryHolder {
		@Override
		public Inventory getInventory() {
			return Bukkit.createInventory(null, 54);
		}
	}
}
